package gncom.qr;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class IntroPage extends Activity {
	private ProgressDialog mProgressDialog;
	private LocationManager locationManager;
	private String locationProvider;
	private String strLatitude;
	private String strLongitude;
	private String strState;
	private String saveUUID = "";
	private boolean flag = true;
	private ConnectivityManager connMgr;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.intro);
		
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		locationProvider = locationManager.getBestProvider(new Criteria(), true);

		
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		locationManager.removeUpdates(locationListener);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		locationManager.removeUpdates(locationListener);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		connMgr = (ConnectivityManager) 
	      getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = connMgr.getActiveNetworkInfo();
		if(ni!=null){
			mProgressDialog = ProgressDialog.show(this, null, "    Loading........");
			locationManager.requestLocationUpdates(locationProvider, 3000, 10, locationListener);
		}else{
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("네트워크연결");
			alert.setMessage("네트워크 연결실패\n네트워크 상태를 확인하세요.");
			alert.setPositiveButton("재시도",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							////////새로고침..
							((IntroPage)(IntroPage.this)).onResume();
						}
					});
			alert.setNegativeButton("취소",
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int whichButton) {
					
				}
			});
			alert.show();
		}
		
	}

	
	private void postQR25() {
		//Toast.makeText(this, strState, Toast.LENGTH_LONG).show();
		
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				HttpURLConnection conn = null;

				try {
					HttpClient client = new DefaultHttpClient();  
					
					saveUUID = getAppPreferences(IntroPage.this, "UUID");
					String postURL;
					if(saveUUID == null || saveUUID.equals("")) {
						postURL = "http://mobile.gncom.co.kr:8080/qr25/mobile/firstlogin.jsp";
					} else {
						postURL = "http://mobile.gncom.co.kr:8080/qr25/mobile/login.jsp";
					}
					
					
					URL mUrl = new URL(postURL);
					conn = (HttpURLConnection)mUrl.openConnection();
					if (conn==null) {
						Toast.makeText(IntroPage.this, "연결에 실패하였습니다.", Toast.LENGTH_LONG).show();
						return;
					}
					if (conn.getResponseCode()!=HttpURLConnection.HTTP_OK) {
						Toast.makeText(IntroPage.this, "연결에 실패하였습니다.", Toast.LENGTH_LONG).show();
						return;
					}
					HttpPost post = new HttpPost(postURL); 
					
					
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					
					TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
					String device = telephonyManager.getDeviceId();

					String uuid = "35"
						+ Build.BOARD.length()%10
						+ Build.BRAND.length()%10
						+ Build.CPU_ABI.length()%10
						+ Build.DEVICE.length()%10
						+ Build.DISPLAY.length()%10
						+ Build.HOST.length()%10
						+ Build.ID.length()%10
						+ Build.MANUFACTURER.length()%10
						+ Build.MODEL.length()%10
						+ Build.PRODUCT.length()%10
						+ Build.TAGS.length()%10
						+ Build.TYPE.length()%10
						+ Build.USER.length()%10;
										
					params.add(new BasicNameValuePair("device", device));
					params.add(new BasicNameValuePair("uuid", uuid));
					params.add(new BasicNameValuePair("latitude", strLatitude));
					params.add(new BasicNameValuePair("longitude", strLongitude));
					
					UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
					post.setEntity(ent);
					HttpResponse responsePOST = client.execute(post);  
					HttpEntity resEntity = responsePOST.getEntity();
						
					if (resEntity != null) {
						Log.i("2.5 QR", EntityUtils.toString(resEntity));
						if(saveUUID == null || saveUUID.equals("")) {
							setAppPreferences(IntroPage.this, "UUID", uuid);
						}
					}
					mHandler.sendEmptyMessage(100);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					mHandler.sendEmptyMessage(-100);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					mHandler.sendEmptyMessage(-100);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					mHandler.sendEmptyMessage(-100);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					mHandler.sendEmptyMessage(-100);
				}finally{
					conn.disconnect();
				}
			}
		});
		thread.start();		
	}
	
	// SharedPreferences 처리
	private void setAppPreferences(Activity context, String key, String value) {
		SharedPreferences pref = context.getSharedPreferences("2.5QR", 0);
		SharedPreferences.Editor prefEditor = pref.edit();
		prefEditor.putString(key, value);
		prefEditor.commit();
	}
	  
	private String getAppPreferences(Activity context, String key) {
		SharedPreferences pref = context.getSharedPreferences("2.5QR", 0);
		String returnValue = pref.getString(key, "");	    
		return returnValue;
	}
	
	// GPS 핸들러
	LocationListener locationListener = new LocationListener() {
		
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			switch (status) {
			case LocationProvider.OUT_OF_SERVICE:
				strState = "현재 상태 : 범위에서 벗어남";
				break;
			case LocationProvider.TEMPORARILY_UNAVAILABLE:
				strState = "현재 상태 : 일시적 불능";
				break;
			case LocationProvider.AVAILABLE:
				strState = "현재 상태 : 사용가능";
				break;
			default:
				break;
			}
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			strState = "현재 상태 : 서비스 사용 가능";
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			strState = "현재 상태 : 서비스 사용 불가";
		}
		
		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			strState = "현재 상태 : 서비스 상태 변경";
			
			strLatitude = location.getLatitude() + "";
			strLongitude = location.getLongitude() + "";
			
			if(!strLatitude.equals("") && !strLongitude.equals("")) {
				if(flag) {
					postQR25();
					flag = false;
				}
			}
		}
	};
	
	// QR WebSite 업로드 핸들러
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 100) {
				mProgressDialog.dismiss();
				//Toast.makeText(IntroPage.this, "초기화 등록에 성공하였습니다.", Toast.LENGTH_LONG).show();
				
				finish();
				startActivity(new Intent(getApplicationContext(), CaptureActivity.class));

			} else if (msg.what == -100) {
				mProgressDialog.dismiss();
				Toast.makeText(IntroPage.this, "네트워크 연결에 실패하였습니다.", Toast.LENGTH_LONG).show();
			}
		}
	};
}